package cn.com.cifi.mars.schedled;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.LogEventEnum;
import cn.com.cifi.mars.entity.SysJob;
import cn.com.cifi.mars.service.CommonService;
import cn.com.cifi.mars.service.DmDmRemovalReportService;
import cn.com.cifi.mars.service.DmDmSupplyMonthlyDetailService;
import cn.com.cifi.mars.service.DmDmValueReportService;
import cn.com.cifi.mars.service.ReportService;
import cn.com.cifi.mars.service.SysJobService;
import cn.com.cifi.mars.util.DateUtils;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.SysLogUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 去化率报表相关同步任务
 */
@Component
@Slf4j
public class SyncRemovalReportTasks {

    @Autowired
    private DmDmValueReportService dmDmValueReportService;

    @Autowired
	private SysJobService sysJobService;
    
    @Autowired
	private DmDmSupplyMonthlyDetailService dmDmSupplyMonthlyDetailService;

    @Autowired
	private DmDmRemovalReportService dmDmRemovalReportService;
    
    @Autowired
	private ReportService reportService;
    
    @Autowired
	private CommonService commonService;

    /**
     *  每天0点开始，每8小时执行一次
     */
    @Scheduled(cron = "0 0 0/8 * * ? ")
    public void sync(){
    	boolean appointIP = commonService.isAppointIP();
		if (!appointIP){
			return;
		}
		SysJob job = sysJobService.selectJobByCode(Constants.ZERO_REMOVAL_RATE);
		LocalDateTime start = null;
		LocalDateTime end = null;
		if (null != job) {
			Integer jobId = job.getId();
			int count = sysJobService.lockJobById(jobId);
			LocalDateTime lastUpdateTime = job.getUpdateTime();
			boolean flag = LocalDateTimeUtils.isValidTime(lastUpdateTime, Constants.THREE);
			if (count == 1 && !flag) {
				try {
					start = LocalDateTime.now();
					// 此处执行定时任务
					String endDate = LocalDate.now().format(DateTimeFormatter.ofPattern(DateUtils.DATE_JFP_STR));
                    syncDo(endDate);
					end = LocalDateTime.now();
				} catch (Exception e) {
					SysLogUtils.addSysLog(LogEventEnum.REFRESH,"去化率报表","去化率报表定时刷新",e.getMessage()+ e);
					log.error(e.getMessage(),e);
				} finally {
					sysJobService.resetJob(job, start, end);
				}
			}else {
				sysJobService.resetStatus(job);
			}
		}
    }

	public void syncDo(String endDate) {
		// 同步全盘货值信息
		ForkJoinTask<Integer> priceTask = ForkJoinPool.commonPool().submit(() -> {
			if (LocalDate.now().getDayOfMonth() == 1){
				dmDmValueReportService.sync(LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern(DateUtils.DATE_JFP_STR)));
			}
            dmDmValueReportService.sync(endDate);
            return 0;
        });
		
		// 同步签约信息DmDmContractDay、DmDmContractMonth
		ForkJoinTask<Integer> contractTask = ForkJoinPool.commonPool().submit(() -> {
			initDmDmContractDayTask();
			initDmDmContractMonthTask();
            return 0;
        });
		
		// 同步月度供货信息DmDmPlanSupplyMonth
		ForkJoinTask<Integer> supplyMonthTask = ForkJoinPool.commonPool().submit(() -> {
			initDmDmPlanSupplyMonthTask();
            return 0;
        });
		
		// 同步月度供货明细信息SupplyMonthlyDetail
		ForkJoinTask<Integer> supplyMonthlyTask = ForkJoinPool.commonPool().submit(() -> {
			priceTask.get();
			contractTask.get();
			initSupplyMonthlyDetailReportTask();
			return 0;
		});
		
		// 同步去化率报表
		ForkJoinTask<Integer> removalReportTask = ForkJoinPool.commonPool().submit(() -> {
			log.info("#######################  同步去化率报表   start  ##################### ");
			priceTask.get();
			contractTask.get();
			supplyMonthTask.get();
			supplyMonthlyTask.get();
			if (LocalDate.now().getDayOfMonth() == 1){
				String lastMonth = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern(DateUtils.DATE_JFP_STR));
				dmDmRemovalReportService.sync(lastMonth);
				//去化率数据处理
				dmDmRemovalReportService.syncRemovalDataJob(lastMonth);
			}
			dmDmRemovalReportService.sync(endDate);
			Thread.sleep(3*60*1000L);
			//去化率数据处理
			dmDmRemovalReportService.syncRemovalDataJob(endDate);
			log.info("#######################  同步去化率报表   end  ##################### ");
			return 0;
		});

		try {
			removalReportTask.get();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
	}
	
	/**
	  * 定时初始化月度供货明细版本数据
    */
	public void initSupplyMonthlyDetailReportTask() {
		log.info("#######################  初始化月度供货明细版本数据任务   start  ##################### ");
		if(LocalDate.now().getDayOfMonth() == 1) {
			String lastMonth =	LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern(DateUtils.DATE_JFP_STR));
			dmDmSupplyMonthlyDetailService.initSupplyMonthlyDetailReport(lastMonth,"");
		}
		String currentYearMonth  = LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyy-MM");
		dmDmSupplyMonthlyDetailService.initSupplyMonthlyDetailReport(currentYearMonth,"");
		log.info("#######################  初始化月度供货明细版本数据任务   end  ##################### ");
	}

	/**
	 * 
	 * 方法描述： 签约数据（天）初始化任务
	 * 创建人：yyd
	 * 创建时间：2019年12月4日 下午2:23:53
	 */
    public void initDmDmContractDayTask() {
		log.info("#######################  签约数据（天）初始化任务   start  ##################### ");
		reportService.initDmDmContractDay();
		log.info("#######################  签约数据（天）初始化任务   end  ##################### ");
    }
    
    /**
	 * 
	 * 方法描述： 签约数据（月度）初始化任务
	 * 创建人：yyd
	 * 创建时间：2019年12月4日 下午2:23:53
	 */
    public void initDmDmContractMonthTask() {
		log.info("#######################  签约数据（月）初始化任务   start  ##################### ");
		reportService.initDmDmContractMonth();
		log.info("#######################  签约数据（月）初始化任务   end  ##################### ");
    }

    /**
   	 * 
   	 * 方法描述： 月度供货数据初始化任务
   	 * 创建人：yyd
   	 * 创建时间：2019年12月4日 下午2:23:53
   	 */
   public void initDmDmPlanSupplyMonthTask() {
	    log.info("#######################  月度供货数据初始化任务   start  ##################### ");
	    reportService.initDmDmPlanSupplyMonth();
		log.info("#######################  月度供货数据初始化任务   end  ##################### ");
   }
	
}

